package com.hxl.tech.gateway.auth.service;


import com.alibaba.fastjson.JSONObject;
import com.hxl.tech.gateway.auth.dao.OpenApiDao;
import com.hxl.tech.gateway.auth.dto.openapi.OpenApiFindDTO;
import com.hxl.tech.gateway.auth.model.OpenApi;
import com.hxl.tech.gateway.common.constant.AppConstant;
import com.hxl.tech.gateway.common.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 开放接口 Service 
 * @author soliddq
 * @date 2023-10-10
 */
@Service
@RequiredArgsConstructor
@Transactional
public class OpenApiService {

    private final OpenApiDao openApiDao;
    private final EntityManager entityManager;

    public OpenApi saveOrUpdate(OpenApi openApi) {

        openApi.setCreateBy("OPEN-API");
        openApi.setCreateTime(LocalDateTime.now());
        OpenApi origOpenApi = this.read(openApi.getApiName());
        if (Objects.isNull(origOpenApi)) {
            entityManager.persist(openApi);
        } else {
            entityManager.merge(openApi);
        }
        String appKey = AppConstant.REDIS_API_PREFIX + openApi.getApiName();
        RedisUtil.set(appKey, JSONObject.toJSONString(openApi), 0, TimeUnit.DAYS);
        return openApi;
    }

    public void delete(String apiName) {

        OpenApi openApi = this.read(apiName);
        if (Objects.nonNull(openApi)) {
            entityManager.remove(openApi);
            String appKey = AppConstant.REDIS_API_PREFIX + apiName;
            RedisUtil.delete(appKey);
        }
    }

    public OpenApi read(String apiName) {

        return openApiDao.read(apiName);
    }

    public List<OpenApi> find(OpenApiFindDTO findDTO) {

        return openApiDao.find(findDTO);
    }

}
